package yhy.pool.book;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.xml.transform.Templates;
import java.util.List;

/**
 * @Author Administrator
 * @Date 2020/5/26 16:20
 **/
public class BookDaoDB implements BookDao {
    /*spring框架用以简化开发*/
    JdbcTemplate template = new JdbcTemplate(BookJDBCUtils.getDataSource());
    String sql = "";

    @Override
    public int insert(Book book) {
        /*判断用户名是否重复
        *若返回为空 则不重复：
            1）准备insert sql
            2）利用JdbcTempate执行sql语句
            3）返回i
         否则，返回-1
        准备sql语句
        * 利用JDBCTemplate执行*/
        Book b = selectByName(book.getName());
        if (b == null) {
            sql = "insert into book(name,press,author,price)values(?,?,?,?)";
            int i = template.update(sql,
                    book.getName(), book.getPress(), book.getAuthor(), book.getPrice());
            return i;
        } else {
            return -1;
        }
    }

    @Override
    public Book selectByName(String name) {
        /*1.准备select语句
        * 2.对于查询语句：
        *    1）queryForObject();返回单条或没有记录
             2）query（）;返回多条记录
             这两个方法需要传入三类参数：sql
                                      new BeanPropertyRowMapper<Book>(Book.class)
                                        作用：查询库中一条记录，自动封装成Book对象
                                      给？占位符
                                        有几个问号，就有几个占位符*/
        sql = "select * from book where name=?";
        try {
            Book book = template.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), name);
            return book;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    @Override
    public List<Book> selectAll() {
        sql = "select * from book";
        try {
            List<Book> books = template.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
            return books;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    @Override
    public int update(int id, Book book) {
        sql = "UPDATE book SET name = ? ,press=?,author=?,price=? WHERE id = ?";
        return template.update(sql, book.getName(), book.getPress(), book.getAuthor(), book.getPrice(), book.getId());
    }

    @Override
    public int delete(int id) {
        sql = "DELETE FROM book WHERE id=?";
        return template.update(sql, id);
    }

    public BookDaoDB() {
        super();
    }
}
